import { Component, OnInit, Input } from '@angular/core';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { EventService } from 'src/app/shared/service/event.service';
import { AlertController } from '@ionic/angular';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { ActionSheetService } from 'ng-zorro-antd-mobile';

@Component({
  selector: 'app-modify-customer-order',
  templateUrl: './modify-customer-order.component.html',
  styleUrls: ['./modify-customer-order.component.scss'],
})
export class ModifyCustomerOrderComponent implements OnInit {
  @Input() tagData: any;
  disCount: any = 0; // 总优惠
  profit: any = 0;   // 总利润
  countArr = [];
  discountArr = [];
  idArr = [];
  stateKey = '';   // 记录发货方式
  stateValue = ''; // 记录发货方式
  flag = false;
  constructor(
    private httpService: HttpService,
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private eventService: EventService,
    private alertController: AlertController,


  ) { }

  ngOnInit() {
    if (this.tagData.data && this.tagData.data.footDiv && this.tagData.data.footDiv.details2) {
      this.tagData.data.footDiv.details2.forEach(e => {
        if (e.left && e.left.profit !== undefined) {
          this.profit = e.right.secondText.label;
        }
        if (e.left && e.left.discount !== undefined) {
          this.disCount = e.right.secondText.label;
        }
      });
    }
    if (this.tagData.data.data && this.tagData.data.footDiv && this.tagData.data.footDiv.details && this.tagData.data.footDiv.details2) {
      // 计算订单金额、成本
      this.updata(this.tagData.data.data, this.tagData.data.footDiv.details);
      setTimeout(() => {
        // 计算优惠、利润等
        this.updataEmit(true, this.tagData.data.footDiv.details, this.tagData.data.footDiv.details2);
      }, 10);
    }
    this.eventService.eventEmit.on('deftSpec', res => {
      this.tagData.data.data[this.appGlobalService.shopGoodsSecondGlobalClickIndex].secondRowLeft.firstText.label = res.label;
    });

    if (this.eventService.eventEmit.listenerCount('auditNow') > 0) {
      this.eventService.eventEmit.removeListener('auditNow');
    }
    this.eventService.eventEmit.on('auditNow', res => {
      if (res.content.isOnlyBack) {
        localStorage.setItem('needRefresh', 'true');
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
        return;
      }
      if (this.profit < 0) {
        this.appGlobalService.showToast("请从新输入优惠金额", 1500, "top");
        return;
      }
      this.countArr = [];
      this.discountArr = [];
      this.idArr = [];
      this.tagData.data.data.forEach((e, index) => {
        if (e.fifthRowRight && e.fifthRowRight.secondRowRight && e.fifthRowRight.secondRowRight.label === '') {
          this.discountArr.push(0);   // 每类商品的优惠
        } else {
          if (e.fifthRowRight) {
            this.discountArr.push(e.fifthRowRight.secondRowRight.label);   // 每类商品的优惠
          }
        }
        this.countArr.push(e.thirdRowRight.inputBox.label);            // 商品数量
        this.idArr.push(e.id);
      });
      if (this.countArr !== []) {
        res.content[res.content.count] = this.countArr.join(',');
      }
      if (this.discountArr !== []) {
        res.content[res.content.discount_price] = this.discountArr.join(',');
      }
      if (this.idArr !== []) {
        if (res.content.shop_order_form_id) {
          res.content[res.content.shop_order_form_id] = this.idArr.join(',');
        } else if (res.content.shop_package_details_id) {
          res.content[res.content.shop_package_details_id] = this.idArr.join(',');
        }
      }
      // 发货方式
      if (this.stateKey === '' && this.stateValue === '') {
        if (this.tagData.data.footDiv && this.tagData.data.footDiv.details2) {
          this.tagData.data.footDiv.details2.forEach(e => {
            if (e.isSelect) {
              res.content[e.right.secondText.key] = e.right.secondText.defaultValue; // 给默认发货方式
            }
          });
        }
      } else if (this.stateKey !== '' && this.stateValue !== '') {
        res.content[this.stateKey] = this.stateValue; // 发货方式
      }

      const params = {
        sessionId: localStorage.getItem("sessionId"),
        content: res.content,
        id: res.id,
      };
      this.httpService.post('application/submit', params, r => {
        if (r.success) {
          if (params.content.back && params.content.back === "refresh") {   // 请求成功 返回上一页
            localStorage.setItem('needRefresh', 'true');
            this.appGlobalService.popTarget();
            this.appGlobalService.goBack();
          }
        }
      });
    });
    const timer1 = setTimeout(() => {
      if (this.tagData.name === 'updateCustomerOrderListEmitTag') {
        // 不需要左边文本展示
        this.eventService.eventEmit.emit('deftA', '1');
        clearTimeout(timer1);
      }
    }, 0);
    const timer2 = setTimeout(() => {
      this.flag = true;
      clearTimeout(timer2);
    }, 100);
  }

  sub(event, submit, item, i, data, details, details2) {
    this.flag = false;
    if (i === 0) {
      item.thirdRowRight.inputBox.label = item.thirdRowRight.inputBox.label - 1;
      if (item.thirdRowRight.inputBox.label <= 0) {
        item.thirdRowRight.inputBox.label = 1;  // 商品数下限
        event.stopPropagation();
        return;
      }
    } else if (i === 1) {
      item.thirdRowRight.inputBox.label = (item.thirdRowRight.inputBox.label - 0) + 1;
      if (item.thirdRowRight.inventory !== undefined && item.thirdRowRight.inputBox.label > item.thirdRowRight.inventory) {
        item.thirdRowRight.inputBox.label = item.thirdRowRight.inventory;  // 商品数上限
        event.stopPropagation();
        return;
      }
    }
    this.updata(data, details);
    this.updataEmit(event, details);

    if (submit !== undefined && submit !== null && submit !== '') {
      submit.content.count = item.thirdRowRight.inputBox.label;
      const params = {
        content: submit.content,
        id: submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        if (!res.success) {
          this.appGlobalService.showToast(res.message, 1500, "middle");
        }
      });
    }
    const timer = setTimeout(() => {
      this.flag = true;
      clearTimeout(timer);
    }, 100);
    event.stopPropagation();
  }

  openPage(link, event, i?) {
    if (i !== '' && i !== undefined) {
      this.appGlobalService.shopGoodsSecondGlobalClickIndex = i;
    }
    this.pageModalService.openPage(link);
    event.stopPropagation();
  }
  // 优惠金额
  changeValue(event, item, data?, details?, submit?) {
    if (item.textType === 'number' && event.detail.value !== 'NaN') {
      if (event.detail.value < 0) {
        this.appGlobalService.showToast("请输入正数", 2000, "top");
        event.stopPropagation();
        return;
      }
      this.updataEmit(event, details);

    }
    event.stopPropagation();
  }
  changeValue_mid(event, submit, item, data, details) {
    if (item.type === 'number' && event.detail.value !== '' && this.flag === true) {
      if (event.detail.value > 0 ) {
        if (item.thirdRowRight.inventory !== undefined && item.thirdRowRight.inputBox.label > item.thirdRowRight.inventory) {
          item.thirdRowRight.inputBox.label = item.thirdRowRight.inventory;  // 商品数上限
          event.stopPropagation();
          return;
        }
      } else if (event.detail.value <= 0) {
        item.thirdRowRight.inputBox.label = 1;
        this.appGlobalService.showToast("最小数量不能低于1", 2000, "top");
        event.stopPropagation();
        return;
      }
      this.updata(data, details);
      this.updataEmit(event, details);
      event.stopPropagation();

      if (submit !== undefined && submit !== null && submit !== '') {
        submit.content.count = item.thirdRowRight.inputBox.label;
        const params = {
          content: submit.content,
          id: submit.id,
          sessionId: localStorage.getItem("sessionId")
        };
        this.httpService.post("application/submit", params, res => {
          if (!res.success) {
            this.appGlobalService.showToast(res.message, 1500, "middle");
          }
        });
      }
    }
    event.stopPropagation();

  }
  getInterger(value) {
    return parseInt(value, 10);
  }

  async deleteItem( i, event, submit, data?, details?, details2?) {

    const alert = await this.alertController.create({
      message: submit.content.text,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: '确定',
          handler: () => {
            const params = {
              content: submit.content,
              id: submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, o => {
              if (o.success) {
                this.tagData.data.data.splice(i, 1);
                this.updata(data, details);
                // 优惠金额
                if (event.detail.value && event.detail.value !== "NaN" && event.detail.value !== undefined && event.detail.value !== null) {
                  this.updataEmit(event, details);
                }
              }
              if (o.message.length > 0) {
                this.appGlobalService.showToast(o.message, 1500, "middle");
              }
            });
          }
        }
      ]
    });
    await alert.present();
    event.stopPropagation();
    return;
  }

  updata(data?, details?) {
    details[0].right.secondText.label = 0;
    details[1].right.secondText.label = 0;
    data.forEach(e => {
      if (e.thirdRowLeft.secondText.label && e.thirdRowLeft.secondRowRight.label1) {
        details[0].right.secondText.label += e.thirdRowLeft.secondText.label * e.thirdRowRight.inputBox.label;      // 金额   数量x单价
        details[1].right.secondText.label += e.thirdRowLeft.secondRowRight.label1 * e.thirdRowRight.inputBox.label;   // 成本   数量x单价
      }
    });
  }
  updataEmit(event, details, details2?) {
    let value = 0;
    let valueDeft = 0;
    this.tagData.data.data.forEach(e => {
      if (e.fifthRowRight && e.fifthRowRight.secondRowRight) {
        if (e.fifthRowRight.secondRowRight.label) {
          value += Number(e.fifthRowRight.secondRowRight.label);
        }
      }
    });
    if (details2) {
      details2.forEach(e => {
        if (e.left && e.left.discount !== undefined) {
          this.disCount = e.right.secondText.label;
        } else {
          if (e.right.secondText && e.right.secondText.label !== undefined && e.right.secondText.label !== null) {
            // 计算商品折扣  商品折扣是不变的
            valueDeft += Number(e.right.secondText.label);
          }
        }

      });
    }
    let profit = 0;
    let profit2 = 0;

    profit = ((details[0].right.secondText.label * 10) - (details[1].right.secondText.label * 10)) / 10 - valueDeft;          // 纯利润
    profit2 = ((details[0].right.secondText.label * 10) - (details[1].right.secondText.label * 10)) / 10 - value - valueDeft; // 减去优惠后的利润

    //  输入的优惠值 大于 纯利润
    if (value > profit) {
      this.disCount = 0;
      this.appGlobalService.showToast("优惠已超出利润", 2000, "middle");
    } else {
      this.disCount = value; // 输入的优惠值
    }
    this.disCount = value; // 优惠金额    总计
    this.profit = profit2; // 利润       总计
    this.appGlobalService.eventService.emit("orderValue", {num3: profit2});
    const res = {
      // num1 成本、  num2 利润
      num1: details[1].right.secondText.label,
      num2: profit2
    };
    this.appGlobalService.eventService.emit("numResults", res);

  }



  modeBtn(item) {
    const that = this;
    const buttons: any = [];
    Object.keys(item.check).forEach((element, index) => {
      buttons.push(element);
    });
    ActionSheetService.showActionSheetWithOptions(
      {
        options: buttons,
        maskClosable: true
      },
      buttonIndex => {
        if (buttonIndex > -1) {
          ActionSheetService.close();
          that.selectItem(item, buttons[buttonIndex]);
        }
      }
    );
  }

  selectItem(item, name) {
    item.defaultText = name;
    this.stateKey = item.key;
    this.stateValue = item.check[name];
  }

}
